﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dev.Control;
using SfcorpDLL.biz;
using GT.ORM;
using Billing;
using Billing.ety;
using GT.ReportDLL.Biz;
using GT.ReportDLL.ety;
using System.Collections;
using DevExpress.XtraBars;
using DevExpress.XtraTreeList.Nodes;
using TT.Common;

namespace Sfcorp.form
{

    public partial class frmAgyBnsBillMain : BaseFormDev
    {
        bizAccount bzAccount;
        bizAgyBns bzAgyBns;
        IList<etyChargeDtl> ilChrgDtl = new List<etyChargeDtl>();
        IList<etyChargeDtl> ilChrgCash = new List<etyChargeDtl>();
        etyBillParams eyBillRq = new etyBillParams();
        type_view_bill tpBill = type_view_bill.bnsCash;
        DataTable dtAccountCross = new DataTable();
        DataProcType tpProcess = DataProcType.NEW;
        FactoryBill bzBill;

        public frmAgyBnsBillMain(IList<etyChargeDtl> chrgDtl, etyBillParams iBillRq, type_view_bill tyBill,DataTable dtAmount,FactoryBill ibzBill)
        {
            InitializeComponent();
            ilChrgDtl = chrgDtl;
            eyBillRq = iBillRq;
            tpBill = tyBill;
            bzBill = ibzBill;
            dtAccountCross = dtAmount;
            Get_I_Bill();
        }

        private void frmAccount_Load(object sender, EventArgs e)
        {
            bzAccount = new bizAccount(global.basSysPara);
            bzAgyBns = new bizAgyBns(global.basSysPara);

            //明细
            ggcChrgDtl.GridView = this.gvChrgDtl;
            ggcChrgDtl.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            string sMapingCols = "CUSTOMER_NAME,ITEM_DESC,IO_FLAG_DESC,CASH_FLAG_DESC,UNIT_DESC,PRICE,QTY ,AMOUNT,INVOICE_NO,CHRG_DESC2,CHRG_DESC3,CHRG_DESC4,CHRG_DESC5,CHRG_FLT20,CHRG_DESC22  ,CHRG_DESC23,CHRG_FLT24,CHRG_DESC26";
            string sMapingHeaderTxt = "客户         ,费目     ,收支        ,交现金        ,单位     ,单价 ,数量,合计  ,收据编号  ,货代公司  ,进出口    ,结算方式  ,作业方式  ,业务单号  ,合作方       ,办单人     ,箱号      ,货物名称";
            ggcChrgDtl.ColumnsMappingCreate(sMapingCols.Replace(" ", ""), sMapingHeaderTxt.Replace(" ", ""));
            this.winUtil.LoadGridLayout(ggcChrgDtl);
            ggcChrgDtl.GridView.OptionsView.ShowGroupPanel = true;

            //汇总
            ggcAccount.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            ggcAccount.GridView.OptionsView.ShowGroupPanel = false;
            ggcAccount.gridView = this.gridView2;

            Refresh(true);

            gridView2.OptionsBehavior.Editable = false;
            gvChrgDtl.OptionsBehavior.Editable = false;

            ggcChrgDtl.GridView.CancelSelection();
            ggcAccount.GridView.CancelSelection();

            //业务分开处理
            if (tpBill == type_view_bill.accBill)
                barSaveBill.Visibility = BarItemVisibility.Always;
            else
                barSaveBill.Visibility = BarItemVisibility.Never;
            BarEnabled();
        }

        private void btnExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            F12();
        }

        private void BarEnabled()
        {
            if (tpBill == type_view_bill.accBill)
            {
                barSaveBill.Visibility = BarItemVisibility.Always;
                
                if (tpProcess == DataProcType.NEW)
                    barSaveBill.Enabled = true;
                else
                    barSaveBill.Enabled = false;
                barBillAdd.Enabled = !barSaveBill.Enabled;
                barBillEdit.Enabled = !barSaveBill.Enabled;
                barBillDele.Enabled = !barSaveBill.Enabled;
            }
        }

        private void BillCacula()
        {
            //double dbGet = 0; 
            double dbTo = 0; 
            double dbCash = 0;
            foreach (etyChargeDtl ey in ilChrgDtl)
            {
                //收
                if (ey.IO_FLAG == "1")
                {
                    if (ey.CASH_FLAG == "1" || tpBill== type_view_bill.accBill)        //现金
                    {
                        dbCash += ey.AMOUNT_DB;
                    }
                }
                else//支
                {
                    if(ey.AMOUNT_DB<0)             //茶水费情况
                        dbCash += ey.AMOUNT_DB;    //要少收现金
                    else
                        dbTo += ey.AMOUNT_DB;
                }

            }
            txtTtlGet.Text = dbCash.ToString().Trim();
            txtTtlTo.Text = dbCash.ToString().Trim();
            lbCustomer.Text = ilChrgDtl[0].CUSTOMER;
            lbCustName.Text = ilChrgDtl[0].CUSTOMER_NAME;
            lblAmountSum.Text = dbCash.ToString().Trim();
            txtTtlTo.Focus();
            txtTtlTo.SelectAll();
            
        }

        private void Get_I_Bill()
        {
            ilChrgCash.Clear();
            foreach (etyChargeDtl ey in ilChrgDtl)
            {
                if (ey.CASH_FLAG == "1" || tpBill== type_view_bill.accBill)
                    ilChrgCash.Add(ey);
            }
        }

        private void Refresh(bool FirstLoad)
        {
            if (FirstLoad == false && tpBill!= type_view_bill.ViewBnsAllBill)     //第一次由业务界面传入，不用再读取
            {
                etyChargeDtl eyChrg = new etyChargeDtl();
                eyChrg.CHRG_FLT20 = eyBillRq.BILL_KEY2;
                ilChrgDtl = bzAgyBns.GetBillResult(eyChrg);
                Get_I_Bill();
            }

            //汇总数据
            GT.ORM.etyChargeDtl eyAccount = new etyChargeDtl();
            switch (tpBill)
            {
                case type_view_bill.bnsCash:
                    eyAccount.INVOICE_NO = ilChrgDtl[0].INVOICE_NO;
                    if (!string.IsNullOrEmpty(eyAccount.INVOICE_NO))
                        dtAccountCross = bzAccount.GetCompChargeCross(eyAccount);       //汇总数据
                    break;
                case type_view_bill.ViewBnsAllBill:
                    //汇总数据
                    eyAccount.CUST_TYPE = type_view_bill.ViewBnsAllBill.ToString();
                    eyAccount.CHRG_FLT20 = eyBillRq.BILL_KEY2;
                    if (!string.IsNullOrEmpty(eyAccount.CHRG_FLT20))
                        dtAccountCross = bzAccount.GetCompChargeCross(eyAccount);       
                    //明细数据
                    ilChrgCash = bzAgyBns.GetBillResult(eyAccount);
                    break;
            }

            //只显示现金收、支
            //明细数据
            ggcChrgDtl.gridView = gvChrgDtl;
            srcBinding.DataSource = new List<etyChargeDtl>();
            srcBinding.DataSource = ilChrgCash;
            ggcChrgDtl.DataSource = srcBinding;
            ggcChrgDtl.AutoColumnWidth();

            ggcAccount.GridView.Columns.Clear();
            scrGrid2.DataSource = dtAccountCross;
            ggcAccount.DataSource = scrGrid2;
            string gridHead = "[PORT_NAM;港口],[IO_FLAG_DESC;收支],[CONTRACT_DATE;日期],[CONTRACT_NO;单号],[CLIENT_NAM;办单人],[CLIENT_CONTACT;联系方式],[WORK_WAY_NAM;作业方式],[SEA_BILL_NO;提单1],[AGENT_BILL_NO;提单2],[PORT_CONTRACT;码头单号],[CNTR;柜号],[CNTR_TYPE;尺寸类型],[ITEM_DESC;费用描述],[AMOUNT;总金额]";
            ggcAccount.ColumnsTranslate(gridHead);
            ggcAccount.AutoColumnWidth();
            ggcAccount.ColumnsTranslate(gridHead);

            if(FirstLoad)
                cTabControl1.SelectedTabPageIndex = 0;
            BillCacula();
        }

        public override etyQuickKey RefreshDate()
        {
            Refresh(false);
            return base.RefreshDate();
        }

        private void btnRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            RefreshDate();
        }

        private void txtTtlTo_EditValueChanged(object sender, EventArgs e)
        {
            lbChangeMoney.Text = (Convert.ToDouble(txtTtlTo.EditValue) - Convert.ToDouble(txtTtlGet.EditValue)).ToString();
        }

        private void tbarSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            F8();
        }

        public override etyQuickKey F8()
        {

            return base.F8();
        }

        private void txtTtlTo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (TT.HelpInfo.MsgBox.ShowQuestionBox("是否保存计费并锁单？"))
                {

                }
            }
        }

        private void barBillAdd_ItemClick(object sender, ItemClickEventArgs e)
        {
            NewData();
        }

        //添加费用
        public override etyQuickKey NewData()
        {
            etyChargeDtl eyBillPara = new etyChargeDtl();
            //F2 添加费用
            if (ilChrgDtl.Count > 0)
            {
                eyBillPara = ilChrgDtl[0];
                eyBillPara.CASH_FLAG = "1";
            }
            frmAgyBnsBillAddNew fmBillAdd = new frmAgyBnsBillAddNew(bzAgyBns, eyBillPara,DataProcType.NEW);
            if (fmBillAdd.ShowDialog() == DialogResult.OK)
            {
                RefreshDate();
            }

            return base.NewData();
        }

        public override etyQuickKey DeleteDate()
        {
            //F3
            etyChargeDtl eyBill = srcBinding.Current as etyChargeDtl;
            if (eyBill == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择帐单明细中的数据进行编辑。");
                return null;
            }
            frmAgyBnsBillAddNew fmBillAdd = new frmAgyBnsBillAddNew(bzAgyBns, eyBill, DataProcType.EDIT);
            if (fmBillAdd.ShowDialog() == DialogResult.OK)
            {
                RefreshDate();
            }
            return base.DeleteDate();
        }

        public override etyQuickKey SaveDate()
        {
            //F4 删除费用
            etyChargeDtl eyBill = srcBinding.Current as etyChargeDtl;
            if (eyBill == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择帐单明细中的数据进行删除。");
                return null;
            }
            if (TT.HelpInfo.MsgBox.ShowQuestionBox("是否删除费用？"
                + "\r\n" + "费用名：" + eyBill.ITEM_DESC
                + "\r\n" + "金额：" + eyBill.AMOUNT)
            )
            {
                bool succ = bzAgyBns.Billing_Del_ChargeDtl(eyBill);
                if (succ)
                {
                    RefreshDate();
                }
                TT.HelpInfo.MsgBox.ShowSuccessFailBox(succ);
            }
            return base.SaveDate();
        }

        private void barBillEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            //F3 编辑费用
            DeleteDate();
        }

        private void barBillDele_ItemClick(object sender, ItemClickEventArgs e)
        {
            //F4 删除费用
            SaveDate();
        }

        private void barSaveBill_ItemClick(object sender, ItemClickEventArgs e)
        {
            SaveBilling();
        }

        //保存计费
        private void SaveBilling()
        {
            if (ilChrgDtl.Count <= 0) return;
            try { splashScreenManager1.ShowWaitForm(); }
            catch { }
            foreach (etyChargeDtl ey in ilChrgDtl)
            {
                if (string.IsNullOrEmpty(ey.AMOUNT) || string.IsNullOrEmpty(ey.PRICE_SEQ))
                {
                    TT.HelpInfo.MsgBox.ShowWarnBox("需收之费用未定义价格，请定义价格后重新计算费用再保存。");
                    try { splashScreenManager1.CloseWaitForm(); }
                    catch { }
                    return;
                }
            }
            bool isSave = bzBill.SaveChargeHdrDtl(ilChrgDtl);
            try { splashScreenManager1.CloseWaitForm(); }
            catch { }
            if (isSave)
            {
                tpProcess = DataProcType.EDITING;
                TT.HelpInfo.MsgBox.ShowSuccessBox("计费成功！");
                //barSaveBill.Visibility = BarItemVisibility.Never;
                this.Close();
            }
            else
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("计费失败！请联系系统管理员。");
            }
        }

    }
}
